package br.com.fatec.cqr.control.mongo;

import java.util.ArrayList;

import br.com.fatec.cqr.control.model.Comando;
import br.com.fatec.cqr.main.Principal;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

public class Update implements Comando {

	@Override
	public String conversao(String texto) {

		String[] split = texto.split("\\(");
		ArrayList<String> lista = new ArrayList<String>();
		String tabela = "";
		for (int i = 0; i < split.length; i++) {
			if (i == 0) {
				int indexOf = split[0].indexOf("db.") + 3;
				int indexOfUpdate = split[0].indexOf(".update");
				tabela = split[0].substring(indexOf, indexOfUpdate);

			} else if (i == 1) {
				String[] split2 = split[1].split(",");

				for (int j = 0; j < split2.length; j++) {
					String[] split3 = split2[j].split(":");
					for (int k = 0; k < split3.length; k++) {
						lista.add(split3[k].replaceAll("\\{", "")
								.replaceAll("\\}", "").replaceAll("\\)", ""));
					}
				}

			}
		}

		/* Execucao do Comando */

		DBCollection coll = Principal.db.getCollection(tabela);

		String chave1 = (lista.get(0));
		String chave2 = (lista.get(2));

		BasicDBObject newDocument = new BasicDBObject();
		newDocument.append("$set", new BasicDBObject().append(lista.get(4),
				lista.get(5).replaceAll("\"", "")));

		BasicDBObject searchQuery = new BasicDBObject().append(chave1,
				chave2.replaceAll("\"", ""));

		coll.update(searchQuery, newDocument);

		return texto.replaceAll(" ", "");

	}

	@Override
	public String expressao() {
		return "^db.*\\.update.*";
	}

}
